package com.i3q360.layui.config;

import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.i3q360.layui.core.shiro.ShiroKit;

@Configuration
public class BeetlConf {

	public static final String BEETLCONF_PREFIX = "beetl";

	@Value("${beetl.templatesPath}")
	private String templatesPath;
	@Value("${beetl.tagroot}")
	private String tagroot;
	@Value("${beetl.tagsuffix}")
	private String tagsuffix;
	

	public Properties getBeetlProperties() {
		Properties properties = new Properties();

		if (StringUtils.isNotEmpty(tagroot)) {
			properties.setProperty("RESOURCE.tagRoot", tagroot);
		}
		if (StringUtils.isNotEmpty(tagsuffix)) {
			properties.setProperty("RESOURCE.tagSuffix", tagsuffix);
		}
		return properties;
	}

	@Bean(name = "beetlConfig")
	public BeetlGroupUtilConfiguration getBeetlGroupUtilConfiguration() {
		BeetlGroupUtilConfiguration beetlGroupUtilConfiguration = new BeetlGroupUtilConfiguration(){
			@Override
			protected void initOther() {
				groupTemplate.registerFunctionPackage("shiro", new ShiroKit());
			}
		};
		
		// 获取Spring Boot 的ClassLoader
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		if (loader == null) {
			loader = BeetlConf.class.getClassLoader();
		}
		beetlGroupUtilConfiguration.setConfigProperties(getBeetlProperties());// 额外的配置，可以覆盖默认配置，一般不需要
		ClasspathResourceLoader cploder = new ClasspathResourceLoader(loader, templatesPath);
		beetlGroupUtilConfiguration.setResourceLoader(cploder);
		beetlGroupUtilConfiguration.init();
		// 如果使用了优化编译器，涉及到字节码操作，需要添加ClassLoader
		beetlGroupUtilConfiguration.getGroupTemplate().setClassLoader(loader);
		return beetlGroupUtilConfiguration;

	}

}
